const OrderModel = require('../models/order.model');
const CartModel = require('../models/cart.model');
const { ValidationError } = require('../middleware/error');

class OrderController {
  // 创建订单
  static async createOrder(req, res, next) {
    try {
      const userId = req.user.id;
      console.log(`[OrderController.createOrder] Creating order for userId: ${userId}`);

      // 验证收货地址
      if (!req.body.shipping_address_id) {
        throw new ValidationError('请选择收货地址');
      }

      // 验证购物车
      const cartValidation = await CartModel.validateItems(userId);
      if (!cartValidation.valid) {
        throw new ValidationError('购物车商品状态异常', {
          cart_items: cartValidation.errors
        });
      }

      // 获取购物车内容
      const cart = await CartModel.getCart(userId);
      if (cart.items.length === 0) {
        throw new ValidationError('购物车为空');
      }

      // 准备订单数据
      const orderData = {
        total_amount: cart.summary.total_amount,
        shipping_address_id: req.body.shipping_address_id,
        customer_remarks: req.body.customer_remarks || null,
        items: cart.items.map(item => ({
          product_id: item.product_id,
          product_name: item.name,
          price: parseFloat(item.price),
          quantity: item.quantity
        }))
      };

      const order = await OrderModel.createOrder(userId, orderData);
      res.status(201).json({
        message: '订单创建成功',
        data: order
      });
    } catch (error) {
      console.error(`[OrderController.createOrder] Error creating order for userId: ${req.user.id}:`, error);
      next(error);
    }
  }

  // 获取用户订单列表
  static async getUserOrders(req, res, next) {
    try {
      const userId = req.user.id;
      console.log(`[OrderController.getUserOrders] Fetching orders for userId: ${userId}`);

      const { page, limit, status } = req.query;
      const orders = await OrderModel.getUserOrders(userId, {
        page: parseInt(page) || 1,
        limit: parseInt(limit) || 10,
        status: status || null
      });

      res.json(orders);
    } catch (error) {
      console.error(`[OrderController.getUserOrders] Error fetching orders for userId: ${req.user.id}:`, error);
      next(error);
    }
  }

  // 获取订单详情
  static async getOrderDetail(req, res, next) {
    try {
      const userId = req.user.id;
      const orderNumber = req.params.orderId;
      console.log(`[OrderController.getOrderDetail] Fetching order ${orderNumber} for userId: ${userId}`);

      const order = await OrderModel.getOrderByNumber(orderNumber, userId);
      res.json({
        success: true,
        data: order
      });
    } catch (error) {
      console.error(`[OrderController.getOrderDetail] Error fetching order ${req.params.orderId} for userId: ${req.user.id}:`, error);
      next(error);
    }
  }

  // 取消订单
  static async cancelOrder(req, res, next) {
    try {
      const userId = req.user.id;
      const orderId = req.params.orderId;
      console.log(`[OrderController.cancelOrder] Cancelling order ${orderId} for userId: ${userId}`);

      const order = await OrderModel.cancelOrder(orderId, userId);
      res.json({
        message: '订单已取消',
        data: order
      });
    } catch (error) {
      console.error(`[OrderController.cancelOrder] Error cancelling order ${req.params.orderId} for userId: ${req.user.id}:`, error);
      next(error);
    }
  }
}

module.exports = OrderController; 